package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.loans.LoanIndexActivity;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.tool.WebViewActivity;
import com.gongpingjialoan.activity.vip.VIPDetailActivity;
import com.gongpingjialoan.adapter.car.DisountCarDetailAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.VIPEb;
import com.gongpingjialoan.bean.VipAppiontCarBean;
import com.gongpingjialoan.cc.Const;
import com.gongpingjialoan.data.LoanData;
import com.gongpingjialoan.data.LoanOrderData;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.AddLikeBoardCast;
import com.gongpingjialoan.utility.AbStrUtil;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.utility.GPSUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.TimeUtils;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.ContactPopup;
import com.gongpingjialoan.view.LoanDialog;
import com.gongpingjialoan.view.PriceRegionView;
import com.gongpingjialoan.view.RLScrollView;
import com.gongpingjialoan.view.VIPBuyDialog;
import com.gongpingjialoan.widget.CheckCarPopup;
import com.gongpingjialoan.widget.CutPricePopup;
import com.gongpingjialoan.widget.OrderSeeCarPopup;
import com.gongpingjialoan.widget.VipOrderSeeCarPopup;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/11/16.
 */
public class SecondDetailFragment extends BaseScrollFragment implements View.OnClickListener, AMap.InfoWindowAdapter, ContactPopup.ContactReslutClickListener {

    private static final int REQUEST_LOAN = 0X0030;
    protected boolean isVisible;

    private boolean isPrepared;

    private boolean isFirst = true;

    private static final int ORDER = 0X0023;

    private static final int MENU = 0X0026;

    private static final int CUTPRICE = 0X0024;

    final int DAIKUAN = 10086;

    private static final int CHECK = 0X0028;

    private static final int PAY = 0X0031;

    private static final int GOCHAT = 0X0025;

    private static final int MEET_TYPE = 101;

    private static final int CUT_TYPE = 102;

    private static final int CHAT_TYPE = 103;


    private static final int COLLECT = 0X0018;

    private static final int PUSH = 0X0019;

    private static final int REQUEST_PAYDETAIL = 104;

    private double latitude, longitude;

    private View view, shangjia, resou_view;

    private ImageView is_certifyImageView, contact_menuImageView;

    private ImageView discount_car_image;

    private Button guyibuButton;

    private LinearLayout seenewcarButton, by_layout, by_layout_image;

    private RLScrollView scroll_view;

    private static final int LOGINING = 0X0392;

    private RelativeLayout flyPagerGuidLayout;

    private LinearLayout hl, hl_linear, rankLinearLayout, discountLinearLayout, eval_layout;

    private TextView status_txt, discount_titleTextView, discount_priceTextView, gerenTextView, discount_rank;

    private RelativeLayout reval_yiRelativeLayout;

    private ViewPager viewPager;

    private TextView mandatory_insurance, examine_insurance, gpj_rank_txt;

    private TextView mTextViewTitle, mTextViewCity, mTextViewCompany, mTextViewRegion, mTextViewYear, numTextView;

    private TextView mTextViewPrice, mTextViewMile, mTextViewVolume, mTextViewControl, mTextViewColor, mTextViewDescription;

    private String domainString, mBrandName, mModelName, mTitle, mYear, mCity, mGpjindex, car_year, car_mouth;

    public String mCompany, mRegion, mPrice, mMile, mVolume, time, brand_slug_zh;

    private String mControl, mColor, mContact, mPhone, mDescription;

    private static final int GUYIYU = 0X1314;

    private String seller_user_id = "";

    private TextView tv_car_source_type;

    private String dealer_id;

    private String mBrandSlug, mModelSlug, sourceType, has_model;

    private String mOrderStatus;

    private String[] mProductImgsUrls, maintenance_images;

    private JSONObject jsonProduct;

    public boolean validation_supported, is_appointed, isCheck;

    private CarBuyDetailActivity carBuyDetailActivity;

    public boolean is4sRange = false;

    private JSONObject price_statisticsJSONObject;

    private String model_detail_slug, car_status, mThumbnailUrl, pub_timeString, model_slug_zh, model_detail_slug_zh;

    private TextView car_id_text, priceRankTextView, noTextView, weiTextView, car_statusTextView;

    private TextView bottom_see_car_txt, bottom_cut_price_txt, pubtimeTextView, imageselectTextView, imageAllTextView;

    private String car_id, qs_tags_string, dealer_category, year_string;

    private boolean is_certify;

    private String price_rank;

    public String eval_price, buy_eval_price = "";

    private JSONArray s4_price_range;

    //原始价格  最低价格 上次价格
    private String origin_price, lowest_price, last_price;

    private JSONArray hlJSONArray;

    private String pub_timestamp;

    private String loan_url;

    private NetDataJson mChatNetDataJson;

    private String source_type;

    private TextView source_txt;

    private LinearLayout qs_tags_ll;

    private LayoutInflater mLayoutInflater;

    private TextView type;

    private ImageView collectImageView;

    private TextView collect_txt, paifangTextView, paifangQTextView;

    private LinearLayout attentionLl;

    private ImageView attentionImageView;

    private TextView attention_txt;

    private int same_model_detail_analysed;

    private String popularity;

    private TextView location_desT;
    private NetDataJson getLoannetDataJson;
    private NetDataJson getOrderNetDataJson;

    public void setCarId(String car_id) {
        this.car_id = car_id;
    }

    private PriceRegionView circleView;

    private NetDataJson mNetCarDetail;

    private NetDataJson orderNetDataJson, checkNetDataJson;

    private NetDataJson cutPriceNetDataJson;

    private NetDataJson deleteNetDataJson;

    private NetDataJson vipOrderNetDataJson;

    private OrderSeeCarPopup mOrderSeeCarPopup;

    private CheckCarPopup mCheckCarPopup;

    private VipOrderSeeCarPopup mVipOrderSeeCarPopup;

    private boolean isVipRegion = false;

    private LinearLayout mLoanLl;

    private TextView loan_txt;

    /**
     * 车主环信id
     */
    private String seller_chat_id, newCarPrice, price_range;

    private String pfString = "", pfCityString = "";

    private MapView mMapView;

    private AMap aMap;

    private LinearLayout collectLl;

    private boolean isLike = false;

    private NetDataJson collectNetDataJson;

    private NetDataJson remindJson;

    private NetDataJson deleteRemindJson;

    public boolean is_reminding;

    private LinearLayout bottom_cut_price_ll;

    private LinearLayout contact_ll;

    private TextView mPricetxt;

    private int chat_type;
    private String char_Contact = "", car_url = "";

    private TextView num_tv;

    private TextView car_status_tv;

    private TextView status_id;

    private TextView day_txt;

    private TextView cut_price, price_title, price_rank_tv;

    private ImageView range_4s;

    private ContactPopup contactPopup;

    private LinearLayout pay_cash_ll;

    private boolean isActive = false;

    final int CHECK_CAR = 1001;

    UserManager mUserManager;

    //1代表检测，2代表砍价，3代表联系客户,4代表贷款买车
    int VipActionType;


    //是否是vip认证车
    boolean vip_supported = false;

    private LoanDialog mLoanDialog;

    private List<LoanData.DataBean.OptionsBean> options = new ArrayList<>();

    View ass_layoutV;

    TextView asse_txtT;

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        VipActionType = 0;
        if (orderNetDataJson != null) {
            orderNetDataJson.cancelTask();
            orderNetDataJson = null;
        }
        if (cutPriceNetDataJson != null) {
            cutPriceNetDataJson.cancelTask();
            cutPriceNetDataJson = null;
        }
        if (mNetCarDetail != null) {
            mNetCarDetail.cancelTask();
            mNetCarDetail = null;
        }

        if (vipOrderNetDataJson != null) {
            vipOrderNetDataJson.cancelTask();
            vipOrderNetDataJson = null;
        }

        if (deleteNetDataJson != null) {
            deleteNetDataJson.cancelTask();
            deleteNetDataJson = null;
        }
        if (mChatNetDataJson != null) {
            mChatNetDataJson.cancelTask();
            mChatNetDataJson = null;
        }
        if (null != collectNetDataJson) {
            collectNetDataJson.cancelTask();
            collectNetDataJson = null;
        }

        if (remindJson != null) {
            remindJson.cancelTask();
            remindJson = null;
        }

        if (deleteRemindJson != null) {
            deleteRemindJson.cancelTask();
            deleteRemindJson = null;
        }
        if (checkNetDataJson != null) {
            checkNetDataJson.cancelTask();
            checkNetDataJson = null;
        }
        if (getLoannetDataJson != null) {
            getLoannetDataJson.cancelTask();
            getLoannetDataJson = null;
        }
        if (getOrderNetDataJson != null) {
            getOrderNetDataJson.cancelTask();
            getOrderNetDataJson = null;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        action = "detail";
        isScrollPage = true;
        view = inflater.inflate(R.layout.include_cardetail_layout, container, false);
        mMapView = (MapView) view.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);
        isPrepared = true;
        mUserManager = new UserManager(getActivity());

        lazyLoad();
        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();
        } else {
            isVisible = false;
        }
    }


    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }
        initView();
        getData();
        isFirst = false;
        //填充各控件的数据
    }


    private void getData() {
        carBuyDetailActivity.showProgressDialog();
        mNetCarDetail = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                isFirst = false;
                carBuyDetailActivity.hidenProgressDialog();
                Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                loadDataSuccess(json);
            }
        });
        mNetCarDetail.setUrl(API.carDetails);
        mNetCarDetail.addParam("car_id", car_id);
        mNetCarDetail.addParam("refer", carBuyDetailActivity.from);
        mNetCarDetail.addParam("lat", UserLocation.getInstance().getLatitude());
        mNetCarDetail.addParam("lng", UserLocation.getInstance().getLongitude());
        mNetCarDetail.request("get");
    }


    //跳转到价格变化页面
    private void gotoPriceChangePage() {
        if (MyPushIntentService.PRICECHANGE.equals(carBuyDetailActivity.fromType)) {
            Intent intent = new Intent(carBuyDetailActivity, PriceAdjustmentRecordActivity.class);
            intent.putExtra("car_id", car_id);
            startActivity(intent);
        }
    }


    private void initView() {
        carBuyDetailActivity = (CarBuyDetailActivity) getActivity();

        aMap = mMapView.getMap();
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceMapClick);
                StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_map", System.currentTimeMillis(), 1.0f));
                Intent intent = new Intent(getActivity(), DealerMapActivity.class);
                intent.putExtra("latitude", latitude);
                intent.putExtra("longitude", longitude);
                startActivity(intent);
            }
        });
        mLayoutInflater = LayoutInflater.from(getActivity());
        ass_layoutV = view.findViewById(R.id.ass_layout);
        ass_layoutV.setOnClickListener(this);
        asse_txtT = (TextView) view.findViewById(R.id.asse_txt);
        paifangTextView = (TextView) view.findViewById(R.id.paifang);
        paifangQTextView = (TextView) view.findViewById(R.id.paifang_q);
        resou_view = view.findViewById(R.id.resou_view);
        discount_rank = (TextView) view.findViewById(R.id.discount_rank);
        range_4s = (ImageView) view.findViewById(R.id.range_4s);
        gerenTextView = (TextView) view.findViewById(R.id.geren);
        shangjia = view.findViewById(R.id.shangjia);
        contact_menuImageView = (ImageView) view.findViewById(R.id.contact_menu);
//        numTextView = (TextView) view.findViewById(R.id.num);
        is_certifyImageView = (ImageView) view.findViewById(R.id.is_certify);
        loan_txt = (TextView) view.findViewById(R.id.loan_txt);
        circleView = (PriceRegionView) view.findViewById(R.id.circleView);
        hl = (LinearLayout) view.findViewById(R.id.hl);
        mLoanLl = (LinearLayout) view.findViewById(R.id.loan_ll);
        mLoanLl.setOnClickListener(this);
        bottom_see_car_txt = (TextView) view.findViewById(R.id.bottom_see_car_txt);
        bottom_cut_price_txt = (TextView) view.findViewById(R.id.bottom_cut_price_txt);
        bottom_cut_price_ll = (LinearLayout) view.findViewById(R.id.bottom_cut_price_ll);
        location_desT = (TextView) view.findViewById(R.id.location_des);
        hl_linear = (LinearLayout) view.findViewById(R.id.hl_linear);
        pubtimeTextView = (TextView) view.findViewById(R.id.pubtimeid);
        car_statusTextView = (TextView) view.findViewById(R.id.car_status);
        rankLinearLayout = (LinearLayout) view.findViewById(R.id.rank_linear);
        noTextView = (TextView) view.findViewById(R.id.no_id);
        weiTextView = (TextView) view.findViewById(R.id.no_wei);
        car_id_text = (TextView) view.findViewById(R.id.car_id_text);
        discount_car_image = (ImageView) view.findViewById(R.id.discount_car_image);
        discount_titleTextView = (TextView) view.findViewById(R.id.discount_car_title);
        discount_priceTextView = (TextView) view.findViewById(R.id.disocunt_price);
        discountLinearLayout = (LinearLayout) view.findViewById(R.id.discount_layout);
        flyPagerGuidLayout = (RelativeLayout) view.findViewById(R.id.flyPagerGuidLayout);
        imageselectTextView = (TextView) view.findViewById(R.id.iamge_select);
        imageAllTextView = (TextView) view.findViewById(R.id.iamge_all);
        status_txt = (TextView) view.findViewById(R.id.status_txt);
        reval_yiRelativeLayout = (RelativeLayout) view.findViewById(R.id.eval_yi);
        eval_layout = (LinearLayout) view.findViewById(R.id.eval_layout);
        viewPager = (ViewPager) view.findViewById(R.id.guidePages);
        guyibuButton = (Button) view.findViewById(R.id.guyigu_view);
        seenewcarButton = (LinearLayout) view.findViewById(R.id.see_new_car_id);
        by_layout = (LinearLayout) view.findViewById(R.id.by_layout);
        by_layout_image = (LinearLayout) view.findViewById(R.id.by_layout_image);

        mTextViewTitle = (TextView) view.findViewById(R.id.car_title);
        mTextViewCity = (TextView) view.findViewById(R.id.car_city);
        mTextViewCompany = (TextView) view.findViewById(R.id.car_comp);
        mTextViewRegion = (TextView) view.findViewById(R.id.car_region);
        mTextViewPrice = (TextView) view.findViewById(R.id.car_price);
        mTextViewMile = (TextView) view.findViewById(R.id.car_mile);
        mTextViewVolume = (TextView) view.findViewById(R.id.car_volume);
        mTextViewControl = (TextView) view.findViewById(R.id.car_control);
        mTextViewColor = (TextView) view.findViewById(R.id.car_color);
        mTextViewDescription = (TextView) view.findViewById(R.id.car_meta);
        mTextViewYear = (TextView) view.findViewById(R.id.car_year);
        priceRankTextView = (TextView) view.findViewById(R.id.price_rank);
        mandatory_insurance = (TextView) view.findViewById(R.id.mandatory_insurance);
        examine_insurance = (TextView) view.findViewById(R.id.examine_insurance);
        gpj_rank_txt = (TextView) view.findViewById(R.id.gpj_rank_txt);
        tv_car_source_type = (TextView) view.findViewById(R.id.tv_car_source_type);
        qs_tags_ll = (LinearLayout) view.findViewById(R.id.qs_tags_ll);
        resou_view.setOnClickListener(this);
        guyibuButton.setOnClickListener(this);
        seenewcarButton.setOnClickListener(this);
        rankLinearLayout.setOnClickListener(this);
        discountLinearLayout.setOnClickListener(this);
        bottom_see_car_txt.setOnClickListener(this);
        shangjia.setOnClickListener(this);

        bottom_cut_price_txt.setOnClickListener(this);
        bottom_cut_price_ll.setOnClickListener(this);
        eval_layout.setOnClickListener(this);
        scroll_view = (RLScrollView) view.findViewById(R.id.scrollview);
        scroll_view.setVisibility(View.GONE);


        collectLl = (LinearLayout) view.findViewById(R.id.collect_ll);
        collectImageView = (ImageView) view.findViewById(R.id.collect_im);
        collect_txt = (TextView) view.findViewById(R.id.collect_txt);

        attentionLl = (LinearLayout) view.findViewById(R.id.attention_ll);
        attentionImageView = (ImageView) view.findViewById(R.id.attention_im);
        attention_txt = (TextView) view.findViewById(R.id.attention_tv);
        contact_ll = (LinearLayout) view.findViewById(R.id.contact_ll);
        contact_ll.setOnClickListener(this);
        mPricetxt = (TextView) view.findViewById(R.id.price_txt);
        num_tv = (TextView) view.findViewById(R.id.num_tv);
        car_status_tv = (TextView) view.findViewById(R.id.car_status_tv);
        status_id = (TextView) view.findViewById(R.id.status_id);
        day_txt = (TextView) view.findViewById(R.id.day_txt);
        cut_price = (TextView) view.findViewById(R.id.cut_price);
        price_title = (TextView) view.findViewById(R.id.price_title);
        price_rank_tv = (TextView) view.findViewById(R.id.price_rank_tv);
        pay_cash_ll = (LinearLayout) view.findViewById(R.id.pay_cash_ll);
        pay_cash_ll.setOnClickListener(this);
    }


    public void setReminding() {
        is_reminding = true;
        attentionImageView.setImageResource(R.drawable.remind_y);
        attention_txt.setText("已关注");
    }


    public void deleteReminding() {
        is_reminding = false;
        attentionImageView.setImageResource(R.drawable.remind_n);
        attention_txt.setText("降价提醒");
    }

    public void loadDataSuccess(JSONObject json) {
        try {
            this.jsonProduct = json.getJSONObject("car_data");
            car_url = jsonProduct.getString("car_url");
            vip_supported = jsonProduct.getBoolean("vip_supported");
            isActive = jsonProduct.getBoolean("seller_active");
            seller_chat_id = jsonProduct.getString("seller_chat_id");
            buy_eval_price = jsonProduct.getString("buy_eval_price");
            seller_user_id = jsonProduct.getString("seller_user_id");
            isLike = jsonProduct.getBoolean("is_liked");
            if (isLike) {
                collectImageView.setImageResource(R.drawable.collect_y);
                collect_txt.setText("已收藏");
            } else {
                collectImageView.setImageResource(R.drawable.collect_n);
                collect_txt.setText("收藏");
            }
            is_reminding = jsonProduct.getBoolean("is_reminding");
            if (is_reminding) {
                attentionImageView.setImageResource(R.drawable.remind_y);
                attention_txt.setText("已关注");
            } else {
                attentionImageView.setImageResource(R.drawable.remind_n);
                attention_txt.setText("降价提醒");
            }
            Utils.LogD("车主环信id ：" + seller_chat_id);

            JSONObject jsonObject = jsonProduct.getJSONObject("loan_info");

            loan_url = jsonObject.getString("loan_url");

            car_status = jsonProduct.getString("car_status");
            if (TextUtils.isEmpty(jsonProduct.getString("lng")) || TextUtils.isEmpty(jsonProduct.getString("lat"))) {
                mMapView.setVisibility(View.GONE);
                view.findViewById(R.id.map_view).setVisibility(View.GONE);
            } else {
                double lng = jsonProduct.getDouble("lng");
                double lat = jsonProduct.getDouble("lat");
                mMapView.setVisibility(View.VISIBLE);
                setMapLocation(lat, lng);

            }
            mCity = jsonProduct.getString("city");
//            if (!"苏州".equals(mCity) && !"成都".equals(mCity)) {
//                loan_txt.setText("首付0元，月供仅需" + jsonObject.getString("zero36repayment") + "元(36期)");
//            }
            if (TextUtils.isEmpty(loan_url) && !"苏州".equals(mCity) && !"成都".equals(mCity)) {
                mLoanLl.setVisibility(View.GONE);
            } else {
                mLoanLl.setVisibility(View.VISIBLE);
            }
            if (!TextUtils.isEmpty(jsonProduct.getString("distance")) && UserLocation.getInstance().getCity().equals(mCity)) {
                double distance = jsonProduct.getDouble("distance") / 1000d;
                BigDecimal b = new BigDecimal(distance);
                double new_distance = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                location_desT.setText("距 " + new_distance + "km");
                location_desT.setVisibility(View.VISIBLE);
            } else {
                location_desT.setVisibility(View.GONE);
            }
            mOrderStatus = jsonProduct.getString("order_status");
            if ("available".equals(mOrderStatus) && "sale".equals(car_status)) {
                pay_cash_ll.setVisibility(View.VISIBLE);
            } else {
                pay_cash_ll.setVisibility(View.GONE);
            }

            model_detail_slug_zh = jsonProduct.getString("model_detail_slug_zh");
            brand_slug_zh = jsonProduct.getString("brand_slug_zh");
            model_slug_zh = jsonProduct.getString("model_slug_zh");
            source_type = jsonProduct.getString("source_type");
            mBrandName = jsonProduct.getString("brand");
            mBrandSlug = jsonProduct.getString("brand_slug");
            sourceType = jsonProduct.getString("source_type");
            mModelName = jsonProduct.getString("model");
            mModelSlug = jsonProduct.getString("model_slug");
            pfString = jsonProduct.getString("emission_standard");
            pfCityString = jsonProduct.getString("emission_available_city");
            dealer_category = jsonProduct.getString("dealer_category");
            time = jsonProduct.getString("time");
            mTitle = jsonProduct.getString("title");
            mGpjindex = jsonProduct.getString("gpj_index");
            mYear = jsonProduct.getString("year");
            year_string = jsonProduct.getString("year_string");

            dealer_id = jsonProduct.getString("dealer_id");

            s4_price_range = jsonProduct.getJSONArray("4s_price_range");
            validation_supported = jsonProduct.getBoolean("validation_supported");
            is_appointed = jsonProduct.getBoolean("is_appointed");
            isCheck = jsonProduct.getBoolean("is_validated");

            mPrice = jsonProduct.getString("price");
//            if (("苏州".equals(mCity) || "成都".equals(mCity))) {
            getLoanData();
//            }


            price_statisticsJSONObject = jsonProduct.getJSONObject("price_statistics");
            domainString = jsonProduct.getString("domain");
            mMile = jsonProduct.getString("mile");

            JSONObject dealer_info = jsonProduct.getJSONObject("dealer_info");
            if (dealer_info.length() > 0) {
                is_certify = dealer_info.getBoolean("is_certify");
                mCompany = dealer_info.getString("company_name");
                mRegion = dealer_info.getString("address");
            } else {
                mCompany = jsonProduct.getString("company_name");
                mRegion = jsonProduct.getString("region");
                is_certify = jsonProduct.getBoolean("is_certify");
            }

            mVolume = jsonProduct.getString("volume");
            mControl = jsonProduct.getString("control");
            has_model = jsonProduct.getString("has_model_detail");
            hlJSONArray = jsonProduct.getJSONArray("highlight_config");
            // mUrl = jsonProduct.getString("url");
            pub_timeString = jsonProduct.getString("pub_time");
            mColor = jsonProduct.getString("color");
            qs_tags_string = jsonProduct.getString("qs_tags_string");
            mContact = jsonProduct.getString("contact");
            mPhone = jsonProduct.getString("phone");
            mDescription = jsonProduct.getString("description");
            car_year = jsonProduct.getString("car_year");
            car_mouth = jsonProduct.getString("car_month");

            model_detail_slug = jsonProduct.getString("model_detail_slug");
            mThumbnailUrl = jsonProduct.getString("thumbnail_url");
            pub_timestamp = jsonProduct.getString("pub_timestamp");

            origin_price = jsonProduct.getString("origin_price");
            lowest_price = jsonProduct.getString("lowest_price");
            last_price = jsonProduct.getString("last_price");

            JSONArray imgs = jsonProduct.getJSONArray("image_urls");
            JSONArray maintain_imgs = jsonProduct.getJSONArray("maintenance_images");
            boolean haveChatId = false;
            if (!TextUtils.isEmpty(seller_chat_id)) {
                haveChatId = true;
            }
            contactPopup = new ContactPopup(getActivity(), this, is_appointed, haveChatId, vip_supported);
            View sview = mLayoutInflater.inflate(R.layout.second_detail_source_item, null);
            source_txt = (TextView) sview.findViewById(R.id.source_txt);
            type = (TextView) sview.findViewById(R.id.type);
            if ("personal".equals(source_type)) {
                type.setText("个");
                type.setBackgroundResource(R.drawable.sort_ge);
                source_txt.setText("个人车源");
                qs_tags_ll.addView(sview);
            } else if ("dealer".equals(source_type) || "cpo".equals(source_type) || "odealer".equals(source_type)) {
                type.setText("商");
                source_txt.setText("商家车源");
                qs_tags_ll.addView(sview);
            }
            if (jsonProduct.getBoolean("cs_clean")) {
                View yview = mLayoutInflater.inflate(R.layout.second_detail_source_item, null);
                source_txt = (TextView) yview.findViewById(R.id.source_txt);
                type = (TextView) yview.findViewById(R.id.type);
                source_txt.setText("已验证车源");
                type.setText("验");
                type.setBackgroundResource(R.drawable.yan_bg);
                qs_tags_ll.addView(yview);
            }
            JSONArray jsonArray = jsonProduct.getJSONArray("qs_tags");
            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {
                View view = mLayoutInflater.inflate(R.layout.second_detail_type_item, null);
                TextView item_source_txt = (TextView) view.findViewById(R.id.item_source_txt);
                String sourceType = jsonArray.get(i).toString();
                item_source_txt.setText(sourceType);
                qs_tags_ll.addView(view);
            }

            same_model_detail_analysed = jsonProduct.getInt("same_model_detail_analysed");
            popularity = jsonProduct.getString("popularity");
            int publishDay = Utils.getDays(pub_timestamp, System.currentTimeMillis());
            int deadline = 0;
            if ("A".equals(popularity)) {
                deadline = 7;
            } else if ("B".equals(popularity)) {
                deadline = 15;
            } else if ("C".equals(popularity)) {
                deadline = 25;
            }
            checkStatus(publishDay, deadline);

            num_tv.setText(AbStrUtil.getNumString(same_model_detail_analysed));

            mProductImgsUrls = new String[imgs.length()];
            for (int i = 0; i < imgs.length(); i++) {
                mProductImgsUrls[i] = (String) imgs.get(i);
            }
            maintenance_images = new String[maintain_imgs.length()];
            for (int i = 0; i < maintenance_images.length; i++) {
                maintenance_images[i] = (String) maintain_imgs.get(i);
            }
        } catch (JSONException e) {
            carBuyDetailActivity.hidenProgressDialog();
            Toast.makeText(getActivity(), "数据异常，请检查网络连接或稍后重试。", Toast.LENGTH_SHORT).show();
            return;
        }

        updateView();
        initLinister();


    }

    private void checkStatus(int publishDay, int deadline) {
        if (publishDay <= deadline) {
            if ("A".equals(popularity)) {
                car_status_tv.setText("畅销车");
            } else if ("B".equals(popularity)) {
                car_status_tv.setText("较畅销车");
            } else if ("C".equals(popularity)) {
                car_status_tv.setText("卖的慢");
                status_id.setText("已上架");
                status_txt.setText(publishDay + "");
                car_status_tv.setTextColor(getResources().getColor(R.color.low_price));
                return;
            }
            status_id.setText("预计");
            status_txt.setText(deadline + "");
            day_txt.setText("天售出");
            car_status_tv.setTextColor(getResources().getColor(R.color.car_status_green_color));
        } else {
            car_status_tv.setText("卖的慢");
            status_id.setText("已上架");
            status_txt.setText(publishDay + "");
            car_status_tv.setTextColor(getResources().getColor(R.color.low_price));
        }
    }





    //是否是首次标价
    private boolean isFristPrice() {
        if (TextUtils.isEmpty(last_price)) {
            return true;
        }
        return false;
    }


    private void updateView() {
        try {
            initImg();
            if (isActive) {
                contact_menuImageView.setImageResource(R.drawable.hy_icon);
            }
            if ("成都".equals(Utils.getCityName(getActivity())) && "成都".equals(mCity)) {
                isVipRegion = true;
            }

            mTextViewTitle.setText(mTitle);
            mTextViewPrice.setText(mPrice);
            mTextViewCity.setText(mCity);
            mTextViewYear.setText(mYear);
            pubtimeTextView.setText(Utils.getTimeByTimestamp(pub_timestamp, System.currentTimeMillis()) + "发布");
            car_id_text.setText("基本信息 （车辆ID：" + car_id + ")");
            if (TextUtils.isEmpty(dealer_id)) {
                shangjia.setVisibility(View.GONE);
//                if (isHaveMap) {
                if (!TextUtils.isEmpty(mRegion)) {
                    gerenTextView.setText("看车地点: " + mRegion);
                }
//                } else {
//                    gerenTextView.setVisibility(View.GONE);
//                }
            } else {
                gerenTextView.setVisibility(View.GONE);
            }
            if (hlJSONArray.length() == 0) {
                hl_linear.setVisibility(View.GONE);
            } else {
                LayoutInflater lp = LayoutInflater.from(getActivity());
                //  highlightMyGridView.setAdapter(new HighLightAdapter(hlJSONArray, getActivity()));
                int size = hlJSONArray.length();
                for (int i = 0; i < size; i++) {
                    View view = lp.inflate(R.layout.highlight_item, null);
                    TextView textView = (TextView) view.findViewById(R.id.text);
                    ImageView networkImageView = (ImageView) view.findViewById(R.id.network);
                    textView.setText(hlJSONArray.getJSONObject(i).getString("name"));
                    ImageLoad.LoadImage(networkImageView, hlJSONArray.getJSONObject(i).getString("thumbnail"), R.drawable.trans, R.drawable.trans, getActivity());
                    if (i == size - 1) view.setPadding(0, 0, DhUtil.dip2px(getActivity(), 10), 0);
                    hl.addView(view);
                }
            }

//            当前标价15万，未降过价（只有首次标价 or 首次标价=最低标价）
//            当前标价15万，可降价0.5万（当前标价>=首次标价 and 当前标价>最低标价）
//            当前标价15万，已降价0.5万（当前标价<首次标价 and 当前标价=最低标价）
//            当前标价15万，已降价0.5万，还可降0.1万（当前标价<首次标价 and 当前标价>最低标价）
            int price_text;
            if (isFristPrice()) {
                cut_price.setText("未降价");
                cut_price.setTextColor(getResources().getColor(R.color.text_details_color));
                price_title.setVisibility(View.GONE);
                price_rank_tv.setVisibility(View.GONE);
                gpj_rank_txt.setText("/");
                gpj_rank_txt.setTextColor(getResources().getColor(R.color.text_details_color));

            } else {
                DecimalFormat df = new DecimalFormat("#.0000");

                double current_p = Double.valueOf(mPrice);
                double origin_p = Double.valueOf(origin_price);
                double lowest_p = Double.valueOf(lowest_price);
                if (lowest_p == origin_p) {
                    cut_price.setText("未降价");
                    cut_price.setTextColor(getResources().getColor(R.color.text_details_color));
                    price_title.setVisibility(View.GONE);
                    price_rank_tv.setVisibility(View.GONE);
                    gpj_rank_txt.setText("/");
                    gpj_rank_txt.setTextColor(getResources().getColor(R.color.text_details_color));
                }
                if (current_p >= origin_p && current_p > lowest_p) {
                    price_text = (int) (Double.valueOf(df.format(current_p - lowest_p)) * 10000);
                    cut_price.setText("可降价");
                    cut_price.setTextColor(getResources().getColor(R.color.car_status_red_color));
                    price_title.setVisibility(View.VISIBLE);
                    price_title.setText("可降价");
                    gpj_rank_txt.setText(price_text + "");
                    price_rank_tv.setVisibility(View.VISIBLE);
                    gpj_rank_txt.setTextColor(getResources().getColor(R.color.car_status_red_color));
                }
                if (current_p < origin_p && current_p == lowest_p) {
                    price_text = (int) (Double.valueOf(df.format(origin_p - current_p)) * 10000);
                    cut_price.setText("已降价");
                    price_title.setText("已降价");
                    cut_price.setTextColor(getResources().getColor(R.color.car_status_red_color));
                    price_title.setVisibility(View.VISIBLE);
                    price_rank_tv.setVisibility(View.VISIBLE);
                    gpj_rank_txt.setText(price_text + "");
                    gpj_rank_txt.setTextColor(getResources().getColor(R.color.car_status_red_color));


                }
                if (current_p < origin_p && current_p > lowest_p) {
                    price_text = (int) (Double.valueOf(df.format(current_p - lowest_p)) * 10000);
                    cut_price.setText("可降价");
                    price_title.setText("可降价");
                    cut_price.setTextColor(getResources().getColor(R.color.car_status_red_color));
                    price_title.setVisibility(View.VISIBLE);
                    price_rank_tv.setVisibility(View.VISIBLE);
                    gpj_rank_txt.setText(price_text + "");
                    gpj_rank_txt.setTextColor(getResources().getColor(R.color.car_status_red_color));
                }
            }
            if (mMile.length() == 0 || mMile.equals("None") || mMile.equals("null"))
                mTextViewMile.setText("—");
            else
                mTextViewMile.setText(mMile + "万公里");

            if (mVolume.length() == 0 || mVolume.equals("None") || mVolume.equals("null"))
                mTextViewVolume.setText("—");
            else
                mTextViewVolume.setText(mVolume + "L");

            if (mControl.length() == 0 || mControl.equals("None") || mControl.equals("null"))
                mTextViewControl.setText("—");
            else
                mTextViewControl.setText(mControl);

            if (mColor.length() == 0 || mColor.equals("None") || mColor.equals("null"))
                mTextViewColor.setText("—");
            else
                mTextViewColor.setText(mColor);
            if (!TextUtils.isEmpty(pfString)) {
                paifangTextView.setText(pfString);
            } else {
                paifangTextView.setText("—");
            }

            if (!TextUtils.isEmpty(pfCityString)) {
                paifangQTextView.setVisibility(View.VISIBLE);
                paifangQTextView.setText("(" + pfCityString + "可迁)");
            }

            if (mCompany.length() == 0 || mCompany.equals("None") || mCompany.equals("null"))
                mTextViewCompany.setText("—");
            else
                mTextViewCompany.setText(mCompany);

            if (is_certify) {
                is_certifyImageView.setImageResource(R.drawable.dealer_renzheng);
            } else {
                is_certifyImageView.setImageResource(R.drawable.delear_weirenzheng);
            }

            if (mRegion.length() == 0 || mRegion.equals("None") || mRegion.equals("null"))
                mTextViewRegion.setText("—");
            else
                mTextViewRegion.setText(mRegion);

            if (mDescription.length() == 0 || mDescription.equals("None") || mDescription.equals("null"))
                mTextViewDescription.setText("联系我时，请说是在公平价上看到的，谢谢！");
            else
                mTextViewDescription.setText(mDescription + "\n" + "联系我时，请说是在公平价上看到的，谢谢！");

            if (jsonProduct.getString("mandatory_insurance").equals("")) {
                mandatory_insurance.setText("—");
            } else {
                mandatory_insurance.setText(jsonProduct.getString("mandatory_insurance"));
            }
            if (jsonProduct.getString("examine_insurance").equals("")) {
                examine_insurance.setText("—");
            } else {
                examine_insurance.setText(jsonProduct.getString("examine_insurance"));
            }


            if (sourceType.equals("personal")) {
                tv_car_source_type.setText("普通个人车源");
            } else if (sourceType.equals("dealer")) {
                tv_car_source_type.setText("优质商家车源");
            } else if (sourceType.equals("odealer")) {
                tv_car_source_type.setText("普通商家车源");
            } else if (sourceType.equals("cpo")) {
                tv_car_source_type.setText("厂商认证二手车");
            } else {
                tv_car_source_type.setText("");
            }

            if ("no".equals(has_model)) {
                eval_layout.setVisibility(View.GONE);
                ass_layoutV.setVisibility(View.GONE);
                reval_yiRelativeLayout.setVisibility(View.VISIBLE);
            } else {
                ass_layoutV.setVisibility(View.VISIBLE);
                eval_price = jsonProduct.getString("eval_price");
                asse_txtT.setText(eval_price + "万 >");
                newCarPrice = jsonProduct.getString("price_bn");
                if (TextUtils.isEmpty(newCarPrice) || "0".equals(newCarPrice)) {
                    eval_layout.setVisibility(View.GONE);
//                    reval_yiRelativeLayout.setVisibility(View.VISIBLE);
                } else {
                    eval_layout.setVisibility(View.VISIBLE);
                    reval_yiRelativeLayout.setVisibility(View.GONE);


//                    double priceCompare = AbStrUtil.get2Double(Double.parseDouble(mPrice) - Double.parseDouble(eval_price));
//                    if (priceCompare < 0) {
//                        double priceCompare1 = -priceCompare;
//                        mPricetxt.setText("比市场均价便宜" + priceCompare1 + "万(新车含税价" + newCarPrice + "万)");
//                    } else if (priceCompare > 0) {
//                        mPricetxt.setText("比市场均价贵" + priceCompare + "万(新车含税价" + newCarPrice + "万)");
//                    } else {
//                        mPricetxt.setText("与公平价估值一致" + "(新车含税价" + newCarPrice + "万)");
//                    }
                    if (s4_price_range.length() >= 2) {

                        is4sRange = true;
//                        range_4s.setVisibility(View.VISIBLE);
                        if (s4_price_range.get(0).equals(s4_price_range.get(1))) {
                            price_range = s4_price_range.getString(0) + "万";
                        } else {
                            price_range = s4_price_range.getString(0) + "万-" + s4_price_range.getString(1) + "万";
                        }
                    }

                    if (s4_price_range.length() > 0) {
                        mPricetxt.setText(newCarPrice + "万 >");
                    } else {
                        mPricetxt.setText(newCarPrice + "万");
                    }
                }
            }

            price_rank = jsonProduct.getString("price_rank");
            JSONArray jsonArray = jsonProduct.getJSONArray("lower_car");
            if (TextUtils.isEmpty(price_rank)) {
                noTextView.setVisibility(View.GONE);
                weiTextView.setVisibility(View.GONE);
                priceRankTextView.setText("—");
                priceRankTextView.setTextColor(getActivity().getResources().getColor(R.color.text_grey_dark));
                discountLinearLayout.setVisibility(View.GONE);
                rankLinearLayout.setEnabled(false);
            } else {
                int mRank = Integer.parseInt(price_rank);
                if (mRank == 1) {
                    priceRankTextView.setText(price_rank);
                    discount_rank.setVisibility(View.GONE);
                    discount_car_image.setVisibility(View.VISIBLE);
                    discount_car_image.setImageResource(R.drawable.gpj);
                    discount_titleTextView.setText("该车已是全网最低价");
                    discount_priceTextView.setText(mPrice + "万");
                } else {
                    discount_rank.setVisibility(View.VISIBLE);
                    discount_car_image.setVisibility(View.GONE);
                    priceRankTextView.setText(price_rank);
                    mRank = mRank - 1;
                    discount_rank.setText("第" + mRank + "名");
                    if (jsonArray.length() > 0) {
                        discount_priceTextView.setText(jsonArray.getJSONObject(0).getString("price") + "万");
                        discount_titleTextView.setText(jsonArray.getJSONObject(0).getString("title"));
                    } else {
                        discountLinearLayout.setVisibility(View.GONE);
                        rankLinearLayout.setEnabled(false);
                    }
                }
            }


            if (price_statisticsJSONObject.length() == 0) {
                circleView.setVisibility(View.GONE);
            } else {
                circleView.setVisibility(View.VISIBLE);
                circleView.setData(mPrice,
                        price_statisticsJSONObject.getString("min_price"),
                        price_statisticsJSONObject.getString("low_limit"),
                        price_statisticsJSONObject.getString("high_limit"),
                        price_statisticsJSONObject.getString("max_price"));
                circleView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        priceLoading();
                    }
                }, 1000);
            }

            JSONArray paramsArray = jsonProduct.getJSONArray("params");
            JSONArray configsArray = jsonProduct.getJSONArray("configs");
            if (paramsArray.length() == 0 && configsArray.length() == 0) {
                seenewcarButton.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            carBuyDetailActivity.hidenProgressDialog();
            Toast.makeText(getActivity(), "数据异常，请检查网络连接或稍后重试。", Toast.LENGTH_SHORT).show();
            return;
        }
        carBuyDetailActivity.loadSuccess(mTitle, car_url, mModelName, mYear, mPrice, mThumbnailUrl);
        scroll_view.setVisibility(View.VISIBLE);
        if ("sale".equals(car_status)) {
            car_statusTextView.setVisibility(View.GONE);
            view.findViewById(R.id.bottom_main_view).setVisibility(View.VISIBLE);
        } else {
            car_statusTextView.setVisibility(View.VISIBLE);
            scroll_view.setPadding(0, 0, 0, 0);
        }
        gotoPriceChangePage();
        carBuyDetailActivity.hidenProgressDialog();
    }


    public void initImg() {
        if (mProductImgsUrls.length == 0) {
            mProductImgsUrls = new String[1];
            mProductImgsUrls[0] = "";
            view.findViewById(R.id.image_layout).setVisibility(View.GONE);
            viewPager.setAdapter(new DisountCarDetailAdapter(mProductImgsUrls, this, false));
        } else {
            if (mProductImgsUrls.length == 1) {
                view.findViewById(R.id.image_layout).setVisibility(View.GONE);
            }
            imageAllTextView.setText("/" + mProductImgsUrls.length);
            flyPagerGuidLayout.setVisibility(View.VISIBLE);
            viewPager.setAdapter(new DisountCarDetailAdapter(mProductImgsUrls, this, true));
        }
        initViewPager();

        if (maintenance_images.length == 0) {
            by_layout.setVisibility(View.GONE);
        } else {
            by_layout_image.removeAllViews();
            int size = maintenance_images.length;
            int margin = DhUtil.dip2px(getActivity(), 10);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(8 * margin, 8 * margin);
            lp.leftMargin = margin;
            for (int i = 0; i < size; i++) {
                ImageView imageView = new ImageView(getActivity());
                imageView.setLayoutParams(lp);
                final int finalI = i;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("imgurls", maintenance_images);
                        intent.setClass(getActivity(), ViewPagerActivity.class);
                        intent.putExtra("currentItem", finalI);
                        getActivity().startActivity(intent);
                    }
                });
                Glide.with(this).load(maintenance_images[i]).centerCrop().into(imageView);
                by_layout_image.addView(imageView);
            }
        }
    }

    /**
     * 初始化一些ViewPager的默认配置
     */
    private void initViewPager() {
        Utils.flySetViewPagerDuration(viewPager, 1000);
        viewPager.addOnPageChangeListener(mOnPageChangeListener);
    }


    public void setApponitNums(int num) {
        if (numTextView != null)
            numTextView.setText(num + "");
    }


    /**
     * 指引页面改监听器
     */
    ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        public void onPageSelected(int index) {
            imageselectTextView.setText(index + 1 + "");
        }

    };

    @Override
    public void onClick(View v) {
        if (v == guyibuButton) {
            Intent intent = new Intent(getActivity(), CarEvalActivity.class);
            intent.putExtra("car_id", carBuyDetailActivity.mProductId);
            intent.putExtra("brand_slug", mBrandSlug);
            intent.putExtra("model_slug", mModelSlug);
            intent.putExtra("mile", mMile);
            intent.putExtra("city", mCity);
            intent.putExtra("year", car_year);
            intent.putExtra("source_type", sourceType);
            intent.putExtra("title", mTitle);
            startActivityForResult(intent, GUYIYU);
        } else if (v == seenewcarButton) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceConfig);
            Intent intent = new Intent(getActivity(), NewCarAcitivity.class);
            intent.putExtra("json_data", jsonProduct.toString());
            startActivity(intent);
        } else if (v == eval_layout) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceEval);
            if (is4sRange) {
                PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceNewCarPriceClick);
                Intent intent = new Intent(getActivity(), NewCarPriceActivity.class);
                String filename = GPJApplication.getInstance().getCategoryData().getLogoByModer(mModelSlug);
                String logo_url =
                        Const.IMG_DOMAIN
                                + GPJApplication.getInstance().getApiUrlFromMeta("brand_model_logo_img")
                                + filename + "?imageView2/0/w/100/h/100";
                intent.putExtra("title", mTitle);
                intent.putExtra("image", logo_url);
                intent.putExtra("price", newCarPrice);
                intent.putExtra("city", mCity);
                intent.putExtra("model_detail", model_detail_slug);
                intent.putExtra("price_range", price_range);
                startActivity(intent);
            }
        } else if (v == discountLinearLayout || v == rankLinearLayout) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceSameCity);
            Intent intent = new Intent();
            intent.setClass(getActivity(), SameCityRankActivity.class);
            intent.putExtra("cityName", mCity);
            intent.putExtra("brand", mBrandSlug);
            intent.putExtra("model", mModelSlug);
            intent.putExtra("model_detail", model_detail_slug);
            intent.putExtra("car_id", car_id);
            intent.putExtra("price_rank", price_rank);
            generateCarSource();
            startActivity(intent);
        } else if (v == shangjia) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceDealer);
            if (!TextUtils.isEmpty(dealer_id)) {
                Intent intent = new Intent(getActivity(), DelearActivity.class);
                intent.putExtra("domain", mCompany);
                intent.putExtra("dealer_id", dealer_id);
                if ("buy_car".equals(carBuyDetailActivity.from)) {
                    intent.putExtra("city", carBuyDetailActivity.filter_city);
                    intent.putExtra("province", carBuyDetailActivity.filter_province);
                } else {
                    intent.putExtra("city", mCity);
                }
                startActivity(intent);
            }
        } else if (v == bottom_see_car_txt) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceVIP);
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceDetection);
            VipActionType = 1;

//            if (vip_supported) {
            if (GPJApplication.getInstance().isLogin()) {
//                    mUserManager = mUserManager.LoadUserInfo();
//                    if (mUserManager.is_vip()) {
                gotoCheck();
//                    } else {
//                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_shigu, "杜绝事故车");
//                        dialog.show();
//                    }

            } else {
                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(it, CHECK);
            }
//            } else {
//                if (GPJApplication.getInstance().isLogin()) {
//                    gotoCheck();
//                } else {
//                    Intent it = new Intent(getActivity(), LoginActivity.class);
//                    startActivityForResult(it, CHECK);
//                }
//            }


            //这边其实是分期购车
        } else if (v == bottom_cut_price_txt || v == bottom_cut_price_ll) {
            if (v == bottom_cut_price_txt) {
                PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceLoanMiddle);
            } else {
                PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceLoanBottom);
            }
            VipActionType = 2;
//            if (vip_supported) {
            if (GPJApplication.getInstance().isLogin()) {
                gotoLoan();
//                if (mUserManager.is_vip()) {

//                        if (!mUserManager.isBuy_car_recommend_flag()) {
//                            Intent it = new Intent(getActivity(), BuyCarVipActivity.class);
//                            startActivity(it);
//                        }
//                    showCutPricePopup(false);

//                } else {
//                    showCutPricePopup(true);
//                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_dijia, "低价买好车");
//                        dialog.show();
//                }

            } else {
                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(it, CUTPRICE);
            }
//            } else {
//                if (GPJApplication.getInstance().isLogin()) {
//
//                    showCutPricePopup(false);
//
//                } else {
//                    Intent it = new Intent(getActivity(), LoginActivity.class);
//                    startActivityForResult(it, CUTPRICE);
//                }
//            }
        } else if (v == mLoanLl) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceLoan);
            VipActionType = 4;
//            if (vip_supported) {
//                if (GPJApplication.getInstance().isLogin()) {
//                    mUserManager = mUserManager.LoadUserInfo();
//                    if (mUserManager.is_vip()) {

            StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_loanBuy", System.currentTimeMillis(), 1f));


//            if (("苏州".equals(mCity) || "成都".equals(mCity))) {
//                showLoanDialog(options);
//            } else {
//                gotoWeb(null, null);
//            }
            gotoLoan();

//                    } else {
//                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_daikuan, "低息放心贷");
//                        dialog.show();
//                    }

//                } else {
//                    Intent it = new Intent(getActivity(), LoginActivity.class);
//                    startActivityForResult(it, DAIKUAN);
//                }
//            } else {
//                if (GPJApplication.getInstance().isLogin()) {
//
//                    StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_loanBuy", System.currentTimeMillis(), 1f));
//                    StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail_loanBuy", System.currentTimeMillis(), 1f));
//                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                    intent.putExtra("url", loan_url);
//                    intent.putExtra("content", "贷款买车");
//                    startActivity(intent);
//
//                } else {
//                    Intent it = new Intent(getActivity(), LoginActivity.class);
//                    startActivityForResult(it, DAIKUAN);
//                }
//            }


        } else if (v == contact_ll) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceContact);
            VipActionType = 3;
            if (GPJApplication.getInstance().isLogin()) {

                if (contactPopup != null)
                    contactPopup.show(contact_ll);

            } else {
                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(it, MENU);
            }

        } else if (v == resou_view) {
            if (!"未降价".equals(cut_price.getText().toString())) {
                Intent intent = new Intent(getActivity(), PriceAdjustmentRecordActivity.class);
                intent.putExtra("car_id", car_id);
                startActivity(intent);
            }
        } else if (v == pay_cash_ll) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceDownPayment);
            if (GPJApplication.getInstance().isLogin()) {
                Intent i = new Intent(getActivity(), PayDetailActivity.class);
                i.putExtra("carName", mTitle);
                i.putExtra("car_id", car_id);
                i.putExtra("type", "car_ordered_record");
                startActivity(i);
            } else {
                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(it, PAY);
            }
        } else if (v == ass_layoutV) {
            assessData();
        }
    }

    private void gotoWeb(String order_id, String user_id) {
        Intent intent = new Intent(getActivity(), WebViewActivity.class);
        if (order_id != null) {
            loan_url = "http://www.eflashloan.com/eflashapp/index.html#" + order_id;
            intent.putExtra("order_id", order_id);
            intent.putExtra("vehicle_value", Double.parseDouble(mPrice) * 10000 + "");
            intent.putExtra("access_ip", GPSUtil.getLocalIpAddress());
            intent.putExtra("source", 1);
            intent.putExtra("user_id", user_id);
            intent.putExtra("loadType", "post");
            intent.putExtra("city", mCity);
        }
        intent.putExtra("content", "贷款买车");
        intent.putExtra("url", loan_url);
        intent.putExtra("type", "detail_flashloan");
        startActivity(intent);
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_flashloan", System.currentTimeMillis(), 1f));

    }


    private void showOrderPopup() {
        if (isYousCars()) {
            return;
        }
        if (is_appointed) {
            Toast.makeText(carBuyDetailActivity, "已预约看车", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isVipRegion) {
            showVipPopup();
        } else {
            if (mOrderSeeCarPopup == null) {
                mOrderSeeCarPopup = new OrderSeeCarPopup(this);
            }
            mOrderSeeCarPopup.showAtLocation(scroll_view, Gravity.BOTTOM, 0, 0);
        }
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_appoint", System.currentTimeMillis(), 1f));
    }


    private void appiontVipCar() {
        if (vipOrderNetDataJson == null) {
            vipOrderNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Gson gson = new Gson();
                    VipAppiontCarBean vipAppiontCarBean = gson.fromJson(json, VipAppiontCarBean.class);
                    if ("success".equals(vipAppiontCarBean.getStatus())) {
                        mVipOrderSeeCarPopup = new VipOrderSeeCarPopup(SecondDetailFragment.this, vipAppiontCarBean, car_id);
                        mVipOrderSeeCarPopup.showAtLocation(scroll_view, Gravity.BOTTOM, 0, 0);
                    } else {
                        Toast.makeText(carBuyDetailActivity, vipAppiontCarBean.getMsg(), Toast.LENGTH_SHORT).show();
                        if (vipAppiontCarBean.getData() != null && vipAppiontCarBean.getData().getAppoint_list().size() > 0) {
                            mVipOrderSeeCarPopup = new VipOrderSeeCarPopup(SecondDetailFragment.this, vipAppiontCarBean, car_id);
                            mVipOrderSeeCarPopup.showAtLocation(scroll_view, Gravity.BOTTOM, 0, 0);
                        }
                    }

                }
            }, 1);
        }
        vipOrderNetDataJson.setUrl(API.vip_appiont);
        vipOrderNetDataJson.addParam("car_id", car_id);
        vipOrderNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    private void showVipPopup() {
        appiontVipCar();
    }


    private void showCutPricePopup(boolean showmsg) {
        if (isYousCars()) {
            return;
        }
        CutPricePopup cutPricePopup = new CutPricePopup(this, showmsg);
        cutPricePopup.showAtLocation(scroll_view, Gravity.BOTTOM, 0, 0);
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_bargain", System.currentTimeMillis(), 1f));
    }


    private void gotoCheck() {


        Intent intent = new Intent();
        intent.setComponent(new ComponentName(getActivity(), VIPDetailActivity.class));
        startActivity(intent);

//        Intent intent = new Intent();
//        intent.setComponent(new ComponentName(getActivity(), CarOrderCheckActivity.class));
//        intent.putExtra("brand", mBrandName);
//        intent.putExtra("model", mModelName);
//        intent.putExtra("city", mCity);
//        intent.putExtra("comeFrom", "SecondDetailFragment");
//        startActivity(intent);



      /*  Intent it = new Intent(getActivity(), OrderCheckCarActivity.class);
        it.putExtra("city",mCity);
        it.putExtra("phone",mPhone);
        it.putExtra("car_id",car_id);
        startActivity(it);*/

       /* if (isYousCars()) {
            return;
        }
        if (isCheck) {
            Toast.makeText(carBuyDetailActivity, "已预约检测", Toast.LENGTH_SHORT).show();
            return;
        }
        mCheckCarPopup = new CheckCarPopup(this);
        mCheckCarPopup.showAtLocation(scroll_view, Gravity.BOTTOM, 0, 0);*/
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_validation", System.currentTimeMillis(), 1f));
    }


    private void generateCarSource() {
        CarSource carSrc = new CarSource();
        carSrc.mCity = mCity;
        carSrc.mTitle = mTitle;
        carSrc.mYear = year_string;
        carSrc.mMile = mMile;
        carSrc.mPrice = Double.parseDouble(mPrice);
        carSrc.mId = Integer.parseInt(car_id);
        carSrc.mThumbnail = mThumbnailUrl;
        carSrc.mTime = time;
        carSrc.hasmodel = has_model;
        // carSrc.mRecommend = object.getString("recommend");
        carSrc.mSourceType = sourceType;
        carSrc.mGpjIndex = Double.parseDouble(mGpjindex);
        carSrc.mQsTags = qs_tags_string;
        carSrc.mSource = domainString;
        carSrc.dealer_category = dealer_category;
        carSrc.is_certify = is_certify;
        carSrc.pubTime = pub_timeString;
        carSrc.brand_zh = brand_slug_zh;
        carSrc.model_zh = model_slug_zh;
        carSrc.model_detail_zh = model_detail_slug_zh;
        carSrc.pub_timestamp = pub_timestamp;
        carSrc.setBrand(mBrandSlug);
        carSrc.setModel(mModelSlug);
        carSrc.mUrl = carSrc.mThumbnail;
        carSrc.origin_price = origin_price;
        carSrc.lowest_price = lowest_price;
        carSrc.last_price = last_price;
        GPJApplication.getInstance().setCarSource(carSrc);
    }


    public void assessData() {
        AssessmentData data = AssessmentData.getInstance();
        data.setBrandName("");
        data.setBrandSlug(mBrandSlug);
        data.setMile(mMile);
        data.setModelDetailName("");
        data.setModelDetailSlug(model_detail_slug);
        data.setModelName(mModelName);
        data.setModelSlug(mModelSlug);
        data.setModelThumbnail("");
        data.setMonth(car_mouth);
        data.setYear(car_year);
//        data.setType(getType());
        data.setCity(mCity);
        data.setCar_id("");

        Intent it = new Intent(getActivity(),
                NewUseCarAssResultActivity.class);
        startActivity(it);
    }


    @Override
    public void phone() {

        UserManager mUserManager = new UserManager(getActivity());
        mUserManager = mUserManager.LoadUserInfo();
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_call", System.currentTimeMillis(), 1f, car_id, mUserManager.getPhone()));
//        StepRecord.recordStep(getActivity(), "拨打电话", mUserManager.getPhone() + ";" + mPhone + ";" + carBuyDetailActivity.mProductId);
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhone));
        startActivity(intent);
    }

    @Override
    public void order() {
        if (GPJApplication.getInstance().isLogin()) {
            showOrderPopup();
        } else {
            Intent it = new Intent(getActivity(), LoginActivity.class);
            startActivityForResult(it, ORDER);
        }
    }

    @Override
    public void online() {
//        if (GPJApplication.getInstance().isLogin()) {
//            gotChat();
//        } else {
//            Intent intent = new Intent(getActivity(), LoginActivity.class);
//            startActivityForResult(intent, GOCHAT);
//        }
    }

    @Override
    public void onVipContact() {
        mUserManager = mUserManager.LoadUserInfo();
        if (mUserManager.is_vip()) {
            if (!mUserManager.isBuy_car_recommend_flag()) {
                Intent it = new Intent(getActivity(), BuyCarVipActivity.class);
                startActivity(it);
            }
            contact();
        } else {
            Intent it = new Intent(getActivity(), VIPDetailActivity.class);
            it.putExtra("from", "detail_contactSeller");
            startActivity(it);

        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {


                case PAY:
                    Intent i = new Intent(getActivity(), PayDetailActivity.class);
                    i.putExtra("carName", mTitle);
                    i.putExtra("car_id", car_id);
                    i.putExtra("type", "car_ordered_record");
                    startActivity(i);
                    break;
                case GUYIYU:
                    has_model = "yes";
                    model_detail_slug = data.getStringExtra("model_deail_slug");
                    eval_price = data.getDoubleExtra("eval_price", 0) + "";
                    newCarPrice = data.getStringExtra("new_car_price");
                    String price_range = data.getStringExtra("4s_price_range");
                    if (!TextUtils.isEmpty(price_range)) {
                        try {
                            s4_price_range = new JSONArray(price_range);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    if (TextUtils.isEmpty(newCarPrice) || "0".equals(newCarPrice)) {
                        eval_layout.setVisibility(View.GONE);
                        reval_yiRelativeLayout.setVisibility(View.GONE);
                    } else {
                        eval_layout.setVisibility(View.VISIBLE);
                        reval_yiRelativeLayout.setVisibility(View.GONE);


                        if (s4_price_range != null && s4_price_range.length() > 0) {
                            mPricetxt.setText(newCarPrice + "万 >");
                        } else {
                            mPricetxt.setText(newCarPrice + "万");
                        }
//                        double priceCompare = AbStrUtil.get2Double(Double.parseDouble(mPrice) - Double.parseDouble(eval_price));
//                        if (priceCompare < 0) {
//                            double priceCompare1 = -priceCompare;
//                            mPricetxt.setText("比市场均价便宜" + priceCompare1 + "万(新车含税价" + newCarPrice + "万)");
//                        } else if (priceCompare > 0) {
//                            mPricetxt.setText("比市场均价贵" + priceCompare + "万(新车含税价" + newCarPrice + "万)");
//                        } else {
//                            mPricetxt.setText("与公平价估值一致" + "(新车含税价" + newCarPrice + "万)");
//                        }
                    }
                    break;
                case ORDER:
                    showOrderPopup();
                    break;
                case CUTPRICE:
                    gotoLoan();
//                    mUserManager = mUserManager.LoadUserInfo();
//                    if (mUserManager.is_vip()) {
//                        showCutPricePopup(false);
//                    } else {
//                        showCutPricePopup(true);
//                    }
//                    if (vip_supported) {
//                        if (mUserManager.is_vip()) {
//                            if (!mUserManager.isBuy_car_recommend_flag()) {
//                                Intent it = new Intent(getActivity(), BuyCarVipActivity.class);
//                                startActivity(it);
//                            }
//                            showCutPricePopup(false);
//                        } else {
//                            showCutPricePopup(true);
//                        }
//                    } else {
//                        showCutPricePopup(false);
//                    }
//                    if (mUserManager.is_vip() || !vip_supported) {
//
//
//                    } else {
//                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_dijia, "低价买好车");
//                        dialog.show();
//                    }
                    break;
                case CHECK:
//                    mUserManager = mUserManager.LoadUserInfo();
//                    if (mUserManager.is_vip() || !vip_supported) {
                    gotoCheck();
//                    } else {
//                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_shigu, "杜绝事故车");
//                        dialog.show();
//                    }


                    break;
                case PUSH:
                    remind();
                    break;
                case COLLECT:
                    collect();
                    break;
                case GOCHAT:
//                    gotChat();
                    break;
                case MENU:


//                    if (vip_supported) {
//                        if (mUserManager.is_vip()) {
//                        contact();
//                            VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_kefu, "客服正在帮您联系卖家,1小时内给您答复,请您稍等...", 11, 14);
//                            dialog.show();
//                        } else {
//                            VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_youxiao, "确保有效车");
//                            dialog.show();
//                        }
//                    } else {
                    if (contactPopup != null)
                        contactPopup.show(contact_ll);
//                    }


                    break;
                case LOGINING:
                    Intent intent = new Intent(getActivity(), ReportActivity.class);
                    intent.putExtra("promo_car_id", car_id);
                    intent.putExtra("fromBuycar", true);
                    startActivity(intent);
                    break;
                case REQUEST_PAYDETAIL:
                    gotoPayDetail();
                    break;

                case CHECK_CAR:
                    isCheck = true;
                    break;

                case DAIKUAN:
                    mUserManager = mUserManager.LoadUserInfo();
                    if (mUserManager.is_vip() || !vip_supported) {

                        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_loanBuy", System.currentTimeMillis(), 1f));
                        StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail_loanBuy", System.currentTimeMillis(), 1f));
                        intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra("url", loan_url);
                        intent.putExtra("content", "贷款买车");
                        startActivity(intent);
                    } else {
                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_daikuan, "低息放心贷");
                        dialog.show();
                    }
                    break;
                case REQUEST_LOAN:
                    getOrderId();
                default:
                    break;
            }

        }
    }



    //预约检测
    public void checkCar(String num) {
        if (checkNetDataJson == null) {
            checkNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    isCheck = true;
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, "预约检测成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        checkNetDataJson.setUrl(API.check_car);
        checkNetDataJson.addParam("car_id", car_id);
        checkNetDataJson.addParam("phone", num);
        checkNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    //预约看车
    public void orderCar(String num, boolean isCheck, final boolean isNeedSendMessage) {
        if (orderNetDataJson == null) {
            orderNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    is_appointed = true;

                    if (contactPopup != null) {
                        contactPopup.setOrderTextView();
                        contactPopup.setIsAppiont(is_appointed);
                    }

                    if (isNeedSendMessage) {
                        if (TextUtils.isEmpty(seller_chat_id)) {
                        } else {
                            sendChatMessage(seller_chat_id, MEET_TYPE, mContact, "", "");
                        }
                    }
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceContactAppointmentSuccessAlert);
                    Toast.makeText(carBuyDetailActivity, "预看车成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        orderNetDataJson.setUrl(API.appoint_car);
        orderNetDataJson.addParam("car_id", car_id);
        orderNetDataJson.addParam("phone", num);
        orderNetDataJson.addParam("validate_car", isCheck ? 1 : 0);
        orderNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }

    /**
     * 发送消息
     *
     * @param toUsername 环信id
     */
    private void sendChatMessage(String toUsername, int type, String contact, String expected_price, String time) {
        StringBuilder msg = new StringBuilder();
        msg.append("你好,我对你发布的");
        msg.append(mTitle);
        if (type == MEET_TYPE) {
            if (TextUtils.isEmpty(time)) {
                msg.append("比较有意向,你什么时候方便带我看车？");
            } else {
                msg.append("比较有意向,");
                msg.append(TimeUtils.timeMonthDayFormat(time));
                msg.append("看车，您方便吗？");
            }

        } else {
            msg.append("比较有意向,我的预算是");
            msg.append(expected_price);
            msg.append("万，价格方面能谈谈吗？");
        }
        StringBuilder msg2 = new StringBuilder();
        if (!TextUtils.isEmpty(contact)) {
            msg2.append(contact).append(",").append(msg.toString());
        } else {
            msg2 = msg;
        }
    }


    //预约看车
    public void orderVipCar(String num, final String date, boolean isCheck, final List<VipAppiontCarBean.DataEntity.AppointListEntity> dataEntities) {
        if (orderNetDataJson == null) {
            orderNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    is_appointed = true;
                    if (contactPopup != null) {
                        contactPopup.setOrderTextView();
                        contactPopup.setIsAppiont(is_appointed);
                    }
                    int size = dataEntities.size();
                    for (int i = 0; i < size; i++) {
                        if (TextUtils.isEmpty(dataEntities.get(i).getChat_id())) {
                        } else {
                            sendChatMessage(dataEntities.get(i).getChat_id(), MEET_TYPE, dataEntities.get(i).getContact(), "", date);
                        }
                    }

                    Toast.makeText(carBuyDetailActivity, "预约成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        orderNetDataJson.setUrl(API.appoint_cip_car);
        orderNetDataJson.addParam("phone", num);
        orderNetDataJson.addParam("date_time", date);
        orderNetDataJson.addParam("validate_car", isCheck ? 1 : 0);
        orderNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    public void cutPrice(String phone, final String expected_price) {
        if (cutPriceNetDataJson == null) {
            cutPriceNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceCutPriceSuccess);
                    Toast.makeText(carBuyDetailActivity, "提交成功", Toast.LENGTH_SHORT).show();
                    if (TextUtils.isEmpty(seller_chat_id)) {
                    } else {
                        sendChatMessage(seller_chat_id, CUT_TYPE, mContact, expected_price, "");
                    }

                    mUserManager = mUserManager.LoadUserInfo();

                    if (vip_supported && mUserManager.is_vip()) {
                        VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_kefu, "客服正在帮您联系卖家,1小时内给您答复,请您稍等...", 11, 14);
                        dialog.show();
                    }

                }
            });
        }
        cutPriceNetDataJson.setUrl(API.cut_price);
        cutPriceNetDataJson.addParam("car_id", car_id);
        cutPriceNetDataJson.addParam("phone", phone);
        cutPriceNetDataJson.addParam("expected_price", expected_price);
        cutPriceNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    public void delete(int id) {
        if (deleteNetDataJson == null) {
            deleteNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    mVipOrderSeeCarPopup.remove();
                    mVipOrderSeeCarPopup.initCarsView();
                    Toast.makeText(carBuyDetailActivity, "取消成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        deleteNetDataJson.setUrl(API.delete_vip);
        deleteNetDataJson.addParam("id", id);
        deleteNetDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    private void setMapLocation(double latitude, double longitude) {

//        mMarkerOption.position(ll);
//        mMarkerOption.snippet("");
//        aMap.addMarker(mMarkerOption);
//        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 15));
        this.latitude = latitude;
        this.longitude = longitude;
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.draggable(false);
        markerOption.anchor(0.5f, 0.5f);
        markerOption.title("当前车源位置");
        LatLng ll = new LatLng(latitude, longitude);
        markerOption.position(ll);
//        markerOption.icon(BitmapDescriptorFactory
//                .fromResource(R.drawable.map_location));
        Marker marker = aMap.addMarker(markerOption);
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 15));
        marker.showInfoWindow();
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getActivity().getLayoutInflater().inflate(
                R.layout.custom_info, null);
        render(marker, infoWindow);
        return infoWindow;
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        titleUi.setText(title);
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }


    //收藏接口
    private void initLinister() {
        collectLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLike) {
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceRemoveFavorite);
                } else {
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceAddFavorite);
                }
                if (GPJApplication.getInstance().isLogin()) {
                    collect();
                } else {
                    Intent it = new Intent(getActivity(), LoginActivity.class);
                    startActivityForResult(it, COLLECT);
                }
            }
        });

        attentionLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (is_reminding) {
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceCancelPriceAttention);
                } else {
                    PointRecordManage.getInstance().addPoint(getActivity(), Piont.SellCarAddPriceAttention);
                }
                if (GPJApplication.getInstance().isLogin()) {
                    remind();
                } else {
                    Intent it = new Intent(getActivity(), LoginActivity.class);
                    startActivityForResult(it, PUSH);
                }
            }
        });

    }

    private void remind() {
        if (is_reminding) {
            deleteRemind();
        } else {
            attention();
        }
        is_reminding = !is_reminding;
    }


    private void collect() {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_like", System.currentTimeMillis(), 1f));
        carBuyDetailActivity.showProgressDialog();
        if (!isLike) {
            collectNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(getActivity().getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    isLike = true;
                    Toast.makeText(getActivity().getApplicationContext(), "收藏成功！", Toast.LENGTH_SHORT).show();
                    collectImageView.setImageResource(R.drawable.collect_y);
                    collect_txt.setText("已收藏");
                    sendCollectChange();
                }
            });
            collectNetDataJson.addParam("car_id", car_id);
            collectNetDataJson.setUrl(API.collectCars);
            collectNetDataJson.request("post");
        } else {
            collectNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(getActivity().getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    carBuyDetailActivity.hidenProgressDialog();
                    isLike = false;
                    Toast.makeText(getActivity().getApplicationContext(), "取消收藏成功！", Toast.LENGTH_SHORT).show();
                    collectImageView.setImageResource(R.drawable.collect_n);
                    collect_txt.setText("收藏");
                    sendCollectChange();
                }
            });
            collectNetDataJson.addParam("ids", car_id);
            collectNetDataJson.addParam("record_type", "like_car");
            collectNetDataJson.setUrl(API.deleteCollectCar);
            collectNetDataJson.request("post");
        }
    }

    private void sendCollectChange() {
        Intent intent = new Intent(AddLikeBoardCast.ADD_REMOVE_LIKE);
        getActivity().sendBroadcast(intent);
    }

    /**
     * 关注
     */
    private void attention() {
        if (remindJson == null) {
            remindJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    is_reminding = true;
                    carBuyDetailActivity.hidenProgressDialog();
                    attentionImageView.setImageResource(R.drawable.remind_y);
                    attention_txt.setText("已关注");
                }
            });

        }
        remindJson.setUrl(API.price_change_remind);
        remindJson.addParam("car_id", car_id);
        remindJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }

    /**
     * 取消关注
     */
    private void deleteRemind() {
        if (deleteRemindJson == null) {
            deleteRemindJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    carBuyDetailActivity.hidenProgressDialog();
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    is_reminding = false;
                    carBuyDetailActivity.hidenProgressDialog();
                    attentionImageView.setImageResource(R.drawable.remind_n);
                    attention_txt.setText("降价提醒");
                }
            });

        }
        deleteRemindJson.setUrl(API.delete_price_change_remind);
        deleteRemindJson.addParam("car_ids", car_id);
        deleteRemindJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }


    @Override
    public void onScrolling() {
        super.onScrolling();
        priceLoading();
    }

    private void priceLoading() {
        boolean visible = scroll_view.isChildVisible(circleView);
        if (visible) {
            if (!circleView.running && !circleView.isAnmi) {
                circleView.start();
            }
        } else {
            if (!circleView.running && circleView.isAnmi) {
                circleView.reset();
            }
        }
    }

    private boolean isYousCars() {
        if (GPJApplication.getInstance().isLogin()) {
            UserManager userManager = new UserManager(getActivity()).LoadUserInfo();
            if (GPJApplication.getInstance().chat_user_id.equals(seller_chat_id) || mPhone.equals(userManager.getPhone())) {
                Toast.makeText(carBuyDetailActivity, "这是您发布的车", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    private void gotoPayDetail() {
        Intent i = new Intent(getActivity(), PayDetailActivity.class);
        i.putExtra("action_type", "detail_order_car");
        StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_order_car", System.currentTimeMillis(), 1f));
        i.putExtra("carName", mTitle);
        i.putExtra("car_id", car_id);
        i.putExtra("type", "car_ordered_record");
        startActivity(i);
    }

    @Subscribe
    public void onEventMainThread(VIPEb VIPEb) {
//        if (VipActionType == 1) {
//            gotoCheck();
//        } else if (VipActionType == 2) {
//            showCutPricePopup();
//        } else
        if (VipActionType == 3) {
            contact();
        }
//        else if (VipActionType == 4) {
//            StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_loanBuy", System.currentTimeMillis(), 1f));
//            StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail_loanBuy", System.currentTimeMillis(), 1f));
//            Intent intent = new Intent(getActivity(), WebViewActivity.class);
//            intent.putExtra("url", loan_url);
//            intent.putExtra("content", "贷款买车");
//            startActivity(intent);
//        }
    }


    private void contact() {
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                carBuyDetailActivity.hidenProgressDialog();
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                carBuyDetailActivity.hidenProgressDialog();
                VIPBuyDialog dialog = new VIPBuyDialog(getActivity(), R.drawable.pic_kefu, "客服正在帮您联系卖家,1小时内给您答复,请您稍等...", 11, 14);
                dialog.show();
            }
        });

        netDataJson.setUrl(API.contact);
        netDataJson.addParam("car_id", car_id);
        netDataJson.request("post");
        carBuyDetailActivity.showProgressDialog();
    }

    private void getLoanData() {
        getLoannetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                LoanData loadData = gson.fromJson(json, LoanData.class);
                options = loadData.getData().getOptions();
                setOptionBypProportion("0%", options);
//                loan_txt.setText("首付0元，月供仅需" + options.get(0).getMonth_pay() + "元(36期)");
            }
        }, 1);
        getLoannetDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.get_loan_get_data);
        getLoannetDataJson.setUseOtherDomain(true);
        getLoannetDataJson.addParam("money", Float.parseFloat(mPrice) * 10000);
        getLoannetDataJson.request("get");
    }

    private void showLoanDialog(List<LoanData.DataBean.OptionsBean> options) {
        if (mLoanDialog == null) {
            mLoanDialog = new LoanDialog(getActivity());
            mLoanDialog.setOnPickResultListener(new LoanDialog.OnPickResultListener() {
                @Override
                public void onResult() {
                    if (GPJApplication.getInstance().isLogin()) {
                        getOrderId();
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), LoginActivity.class);
                        startActivityForResult(intent, REQUEST_LOAN);
                    }

                }
            });
        }
        mLoanDialog.show(options);
    }

    private void getOrderId() {
        getOrderNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                LoanOrderData loanOrderData = gson.fromJson(json, LoanOrderData.class);
                String order_id = loanOrderData.getData().getOrder_no();
                String use_id = loanOrderData.getData().getUser_id();
                mLoanDialog.dismiss();
                gotoWeb(order_id, use_id);

            }
        }, 1);
        getOrderNetDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.loan_get_order_id);
        getOrderNetDataJson.addParam("source", 1);
        getOrderNetDataJson.setUseOtherDomain(true);
        getOrderNetDataJson.request("post");

    }


    private void setOptionBypProportion(String proportion, List<LoanData.DataBean.OptionsBean> jsonArray) {
        if (jsonArray == null) {
            return;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            LoanData.DataBean.OptionsBean data = jsonArray.get(i);
            if (proportion.equals(data.getProportion())) {

                int month_pay = new BigDecimal(data.getMonth_pay()).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                loan_txt.setText("首付0元，月供仅需" + month_pay + "元(36期)");
            }

        }
    }

    private void gotoLoan() {
        Intent it = new Intent(getActivity(), LoanIndexActivity.class);
        it.putExtra("from", "car_detail");
        it.putExtra("price", mPrice);
        it.putExtra("brand", mBrandSlug);
        it.putExtra("brand_zh", mBrandName);
        it.putExtra("model", mModelSlug);
        it.putExtra("model_zh", mModelName);
        it.putExtra("modeldetail", model_detail_slug_zh);
        it.putExtra("year_string", DhUtil.getYearFromDetail(year_string));
        it.putExtra("mile", DhUtil.getMileFromDetail(mMile));

        startActivity(it);
    }
}
